class User < ActiveRecord::Base
  set_primary_key "user_id"

  after_create :create_root
  after_destroy :clean_up
  
  has_many :catalogs,
           :class_name => "Catalog",
           :foreign_key => "user_id",
           :dependent => true
         
  has_one :root_catalog,
          :class_name => "Catalog",
          :foreign_key => "user_id",
          :conditions => "catalogs.parent_id is null"
        
  has_many :comments,
           :class_name => "Comment",
           :foreign_key => "picture_id",
           :dependent => true
        
  has_and_belongs_to_many :users_given_friendship,
                          :class_name => "User",
                          :join_table => "friends",
                          :foreign_key => "user_id_primary",
                          :association_foreign_key => "user_id_secondary"                          
                        
  has_and_belongs_to_many :users_gave_you_friendship,
                          :class_name => "User",
                          :join_table => "friends",
                          :foreign_key => "user_id_secondary",
                          :association_foreign_key => "user_id_primary"
                        
  validates_presence_of :username,
                        :password,
                        :first_name,
                        :last_name,
                        :email

  validates_uniqueness_of :username

  validates_length_of :password,
                      :minimum => 8,
                      :message => "should be at least 8 at most 255 characters long"

  validates_format_of :email,
                      :with => /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i,
                      :message => "must have valid format"

  validates_confirmation_of :password
  attr_accessor :password_confirmation

  def password
    @password
  end

  def password=(pwd)
    @password = pwd
    self.hashed_password = User.encrypted_password(self.password)
  end

  def self.authenticate(name, password)
    user = self.find_by_username(name)
    if user
      expected_password = encrypted_password(password)
      if user.hashed_password != expected_password
	user = nil
      end
    end
    user
  end

  private

  def create_root
    Catalog.create(:name   => self.username,
                   :owner  => self,
                   :access => 0)
                 
    puts "#{RAILS_ROOT}/#{self.username}"
    # Create the phisical directory.
    FileUtils.mkdir("#{RAILS_ROOT}/image_data/#{self.username}", :mode => 0700)
  end

  def clean_up
    # Remove the phisical directory.
    FileUtils.rmdir("#{RAILS_ROOT}/image_data/#{self.username}")
  end
  
  def self.encrypted_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
